package cn.gemframe.security.config;

import cn.gemframe.common.constant.Constants;
import cn.gemframe.config.security.GemTokenProperties;
import cn.gemframe.constant.GemConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/***
 * 认证服务器配置
 */
@Configuration
@EnableAuthorizationServer
public class GemAuthorizeConfig extends AuthorizationServerConfigurerAdapter {

	@Autowired
	private GemTokenProperties gemTokenProperties;

	@Autowired
	private RedisConnectionFactory redisConnectionFactory;

	/***
	 * 配置客户端信息
	 * @param clients
	 * @throws Exception
	 */
	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		// 内存存储
		clients.inMemory()
				// clientId 配置文件里面的配置就失效
				.withClient(GemConstant.Auth.CLIENT_ID_NAME)
				// clientSecret 配置文件里面的配置就失效
				.secret(GemConstant.Auth.CLIENT_ID_PASS)
				// 支持的认证方式
				.authorizedGrantTypes(Constants.AuthorizedGrantTypes.AUTHORIZATION_CODE,
						Constants.AuthorizedGrantTypes.CLIENT_CREDENTIALS,
						Constants.AuthorizedGrantTypes.REFESH_TOKEN,
						Constants.AuthorizedGrantTypes.PASSWOED,
						Constants.AuthorizedGrantTypes.IMPLICIT)
				// token有效时间
				.accessTokenValiditySeconds(gemTokenProperties.getAccessTokenExpire())
				// refreshToken的有效时间
				.refreshTokenValiditySeconds(gemTokenProperties.getRefreshTokenExpire())
				.scopes("all");
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
		security.tokenKeyAccess("isAuthenticated()");
//		security
//				.tokenKeyAccess("isAuthenticated()")
//				.allowFormAuthenticationForClients();
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
					//token存放redis
		endpoints.tokenStore(redisTokenStore());
	}

	@Bean
	public TokenStore redisTokenStore() {
		return new RedisTokenStore(redisConnectionFactory);
	}
}
